<script setup>
import { ref } from "vue";
import useUserStore from "@/stores/user";
import { updateUserInfoApi } from "@/api/user";
import { ElMessage } from "element-plus";
const userStore = useUserStore();

const userForm = ref(userStore.userInfo);
const userFormRef = ref(null);
const userFormRules = {
  nickname: [
    { required: true, message: "请输入用户昵称", trigger: "blur" },
    {
      pattern: /^\S{1,10}$/,
      message: "昵称必须是1-10位的非空字符串",
      trigger: "blur",
    },
  ],
  email: [
    { required: true, message: "请输入用户邮箱", trigger: "blur" },
    { type: "email", message: "邮箱格式不正确", trigger: "blur" },
  ],
};

// 表单重置(清除错误提示信息与数据还原)
const reset = () => {
  userFormRef.value.resetFields();
};

// 提交表单数据
const onSubmit = () => {
  userFormRef.value.validate(async (valid) => {
    if (!valid) return;

    // ajax请交数据实现更新
    const { data: res } = await updateUserInfoApi(userForm.value);
    // 失败
    if (res.code !== 0) return ElMessage.error(res.message);
    // 成功
    ElMessage.success(res.message);
    // 更新pinia中的数据
    userStore.getUserInfo();
  });
};
</script>

<template>
  <el-card class="box-card">
    <template #header>
      <div class="card-header">
        <h3>用户资料</h3>
      </div>
    </template>
    <!-- 表单 -->
    <el-form
      :model="userForm"
      :rules="userFormRules"
      ref="userFormRef"
      label-width="100px"
    >
      <el-form-item label="登录名称">
        <el-input v-model="userForm.username" disabled></el-input>
      </el-form-item>
      <el-form-item label="用户昵称" prop="nickname">
        <el-input
          v-model="userForm.nickname"
          minlength="1"
          maxlength="10"
        ></el-input>
      </el-form-item>
      <el-form-item label="用户邮箱" prop="email">
        <el-input v-model="userForm.email"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">提交修改</el-button>
        <el-button @click="reset">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<style scoped></style>
